package com.oliver.oliveraiagent.app;

import com.oliver.oliveraiagent.advisor.MyLoggerAdvisor;
import com.oliver.oliveraiagent.chatMemory.MySQLBasedChatMemory;
import com.oliver.oliveraiagent.rag.QueryRewriter;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.rag.preretrieval.query.transformation.QueryTransformer;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

/**
 * @ClassName LoveApp
 * @Description TODO
 * @Author snow
 * @Date 2025/5/1 23:14
 **/

/**
 * 恋爱专家
 */
@Component
@Slf4j
public class LoveApp {

    private final ChatClient chatClient;

    @Resource
    private VectorStore loveAppVectorStore;

//    @Resource
//    private VectorStore pgVectorVectorStore;


    private static final String SYSTEM_PROMPT = "扮演深耕恋爱心理领域的专家。开场向用户表明身份，告知用户可倾诉恋爱难题。" +
            "围绕单身、恋爱、已婚三种状态提问：单身状态询问社交圈拓展及追求心仪对象的困扰；" +
            "恋爱状态询问沟通、习惯差异引发的矛盾；已婚状态询问家庭责任与亲属关系处理的问题。" +
            "引导用户详述事情经过、对方反应及自身想法，以便给出专属解决方案。";

    record LoveReport(String title, List<String> suggestions) {
    }

    public LoveApp(ChatModel dashscopeChatModel, MySQLBasedChatMemory mySQLBasedChatMemory) {
        String fileDir = System.getProperty("user.dir") + "/chat-memory";
        // 初始化基于文件的对话记忆
//        ChatMemory chatMemory = new FileBasedChatMemory(fileDir);
        // 初始化基于内存的对话记忆
//        ChatMemory chatMemory = new InMemoryChatMemory();
        //  基于Mysql的对话记忆
        ChatMemory chatMemory = mySQLBasedChatMemory;
        chatClient = ChatClient.builder(dashscopeChatModel)
//                .defaultSystem(SYSTEM_PROMPT + "每次对话后都要生成恋爱报告，标题为{用户名}的恋爱报告，内容为建议列表")
                .defaultSystem(SYSTEM_PROMPT)
                .defaultAdvisors(
                        //  会话记忆前置监控器
                        new MessageChatMemoryAdvisor(chatMemory),
                        //  自定义日志
                        new MyLoggerAdvisor()
                        // 重新阅读
//                        new ReReadingAdvisor()
                )
                .build();
    }


    /**
     * 发起聊天
     *
     * @param message
     * @param chatId
     * @return
     */
    public String doChat(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec ->
                        // 当前你想要去哪一个对话中获取上下文
                        spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                                //  指令你要获取历史消息的条数
                                .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    /**
     * 发起聊天
     *
     * @param message
     * @param chatId
     * @return
     */
    public String doChat(String message, String chatId,Long userId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec ->
                        // 当前你想要去哪一个对话中获取上下文
                        spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                                //  指令你要获取历史消息的条数
                                .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    /**
     * 异步化方式返回信息
     * @param message
     * @param chatId
     * @return
     */
    public Flux<String> doChatByStream(String message, String chatId) {
        return chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .stream()
                .content();
    }

    /**
     * 异步化方式返回信息
     * @param message
     * @param chatId
     * @return
     */
    public Flux<String> doChatByStreamByUserId(String message, String chatId,Long userId) {
        return chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .stream()
                .content();
    }



    /**
     * 发起聊天并生成恋爱报告（格式化输出）
     *
     * @param message
     * @param chatId
     * @return
     */
    public LoveReport doChatWithReport(String message, String chatId) {
        LoveReport loveReport = chatClient
                .prompt()
                .user(message)
                .advisors(spec ->
                        // 当前你想要去哪一个对话中获取上下文
                        spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                                //  指令你要获取历史消息的条数
                                .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .entity(LoveReport.class);
        log.info("loveReport:{}", loveReport);
        return loveReport;
    }


    @Resource
    private QueryRewriter queryRewriter;

    public String doChatWithRag(String message, String chatId) {
        //  查询重写
        String rewriteMessage = queryRewriter.doQueryRewrite(message);

        ChatResponse chatResponse = chatClient
                .prompt()
                .user(rewriteMessage)
                .advisors(spec ->
                        // 当前你想要去哪一个对话中获取上下文
                        spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                                //  指令你要获取历史消息的条数
                                .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                //  应用 RAG 增强检索服务（基于内存向量存储）
                .advisors(new QuestionAnswerAdvisor(loveAppVectorStore))
                //  应用 RAG 增强检索服务（基于 PgVector 向量存储）
//                .advisors(new QuestionAnswerAdvisor(pgVectorVectorStore))
                //  应用 RAG 增强检索服务（条件过滤查询）
//                .advisors(LoveAppRagCustomAdvisorFactory
//                        .createRagCustomAdvisor(loveAppVectorStore,"已婚")
//                )
                .call()
                .chatResponse();

        String content = chatResponse.getResult().getOutput().getText();
        log.info("rag content: {}", content);
        return content;
    }

    //  云RAG
    @Resource
    private Advisor loveAppRagCloudAdvisor;

    public String doChatWithCloudRag(String message, String chatId) {
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(message)
                .advisors(spec ->
                        // 当前你想要去哪一个对话中获取上下文
                        spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                                //  指令你要获取历史消息的条数
                                .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                //  应用增强检索服务
                .advisors(loveAppRagCloudAdvisor)
                .call()
                .chatResponse();

        String content = chatResponse.getResult().getOutput().getText();
        log.info("rag content: {}", content);
        return content;
    }

    @Resource
    private ToolCallback[] allTools;

    /**
     * 发起聊天并使用工具
     * @param message
     * @param chatId
     * @return
     */
    public String doChatWithTools(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .tools(allTools)
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    //  MCP 客户端调用
    @Resource
    private ToolCallbackProvider toolCallbackProvider;

    /**
     * 以 MCP 的方式查询
     * @param message
     * @param chatId
     * @return
     */
    public String doChatWithMCP(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .tools(toolCallbackProvider)
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }


}

